package com.app.micaihu.view.newsdetail;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.TextAppearanceSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.viewpager.widget.ViewPager;

import com.android.volley.VolleyError;
import com.app.micaihu.R;
import com.app.micaihu.base.BaseOldActivity;
import com.app.micaihu.base.bean.DataBean;
import com.app.micaihu.bean.comment.NewsComment;
import com.app.micaihu.bean.news.GalleryEntity;
import com.app.micaihu.bean.news.ImageDetailBean;
import com.app.micaihu.bean.news.RecommendGalleryEntity;
import com.app.micaihu.configure.AppConfigTools;
import com.app.micaihu.configure.Config;
import com.app.micaihu.configure.TypeConstant;
import com.app.micaihu.configure.URIContant;
import com.app.micaihu.custom.view.CustomImageView;
import com.app.micaihu.custom.view.HackyViewPager;
import com.app.widget.LoadView;
import com.app.micaihu.custom.view.PhotoImageView;
import com.app.micaihu.custom.view.VerticalRelativeLayout;
import com.app.micaihu.listener.CommentListener;
import com.app.micaihu.listener.HttpListener;
import com.app.micaihu.manager.UserInforManager;
import com.app.micaihu.utils.AppShareUtils;
import com.app.micaihu.utils.CollectUtils;
import com.app.micaihu.utils.CommentUtils;
import com.app.micaihu.utils.DialogUtils;
import com.app.micaihu.utils.OkHttp3Helper;
import com.app.micaihu.view.newsdetail.adapter.ImageDetailAdapter;
import com.app.micaihu.view.newsdetail.view.ImageAboutView;
import com.app.micaihu.view.user.userinfo.activity.MyHomepageDynamicActivity;
import com.app.utils.util.StringUtils;
import com.app.utils.util.ToastUtils;
import com.app.utils.util.ViewSizeUtils;
import com.app.utils.util.animotion.AppAnimotionuUtils;
import com.app.utils.util.image.LoadImageUtils;
import com.app.utils.util.osutils.StatusBarUtils;
import com.app.utils.util.view.SectorProgressView;
import com.blankj.utilcode.constant.PermissionConstants;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.google.gson.reflect.TypeToken;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.ValueAnimator;
import com.umeng.socialize.UMShareAPI;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Guo on 2016/7/29.
 * <p/>
 * 图库详情:
 */
public class ImageDetailActivity extends BaseOldActivity implements View.OnClickListener, ViewPager.OnPageChangeListener, ImageAboutView.OnImageDetailAboutClickListener, VerticalRelativeLayout.OnTouchMoveListener, PhotoImageView.ImagePhotoViewListener {

    private HackyViewPager hackyImageViewPager;//viewpager
    private TextView tvComment;//发表评论的布局
    private TextView tvCommentSum;//评论数
    private TextView mShareSum;//分享总数
    private RelativeLayout rlCommentContainer;///点击去看评论的布局
    private ImageView ivCollection;//收藏
    private ImageView ivShare;//分享
    private Intent intent;//
    private String articleId;//文章id
    private String pageSourceType;//文章源
    private LoadView lvLoadView;
    private ImageDetailAdapter imageDetailAdapter;//viewpager的适配器
    private ImageDetailBean imageDetailBean;//当前图库的实体类
    //    private ScrollView svContent;//描述的scrollview
    private TextView tvContent;//描述的tv文本
    private boolean isFullScreen;//是否图片是全屏显示的


    private TranslateAnimation outScreenTop;//从顶部出去的动画
    private TranslateAnimation inScreenTop;//从顶部进入的动画

    private CustomImageView authorHeadView;//作者头像
    private ImageView ivAppLeft;
    private TextView tvAppTitle;//title
    private ImageView ivAppRight;//title右边图标

    private boolean misScrolled;//标记是否是viewpager最后一张的变量
    private ImageAboutView imageAboutView;//相关新闻的页面view


    private CommentListener mCommentListener;//评论监听
    private AppShareUtils mShareUtils;//分享工具
    private static SectorProgressView crPv;

    public static final int START = 1;
    public static final int END = 2;
    private int currentPosition = 0;//当前图片的posiiton，默认为0

    private final int persent = 6;//滑动距离的百分比
    private final int AnimalDuration = 400;


    private static final int SUCCESS = 1010;
    private static final int FAIL = 1011;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SUCCESS:
                    String filePath = (String) msg.obj;
                    ToastUtils.makeText(getResources().getString(R.string.detail_image_down_prompt));
                    break;
                case FAIL:
                    ToastUtils.makeText(getResources().getString(R.string.neterror));
                    break;
            }
        }
    };
    private View downLoadView;//下载弹窗的view
    private HashMap<String, Object> dialogParams;
    private VerticalRelativeLayout vrlContainer;
    private int heightPixels;
    private LinearLayout trspTitle;


    private LinearLayout llBottom;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isInit = false;
        super.onCreate(savedInstanceState);
        pageConfigNotify = true;
        //将BaseActivity 的背景设置为透明
        getIntentData();
        setContentView(R.layout.activity_imagedetail);
        StatusBarUtils.setupStatusBarView(this, R.color.common_bg_color_8, R.color.common_bg_color_8);
        //改变通知栏顶部
        initView();
        initListener();
        loadData();


    }

    /**
     * 请求数据
     */
    private void loadData() {
        Map<String, String> params = new HashMap<>();
        getParams(params);
        addPostCacheRequest(URIContant.IMAGEDETAIL, new TypeToken<DataBean<ImageDetailBean>>() {
        }.getType(), params, new HttpListener<DataBean<ImageDetailBean>>() {
            @Override
            public void onStart() {
                super.onStart();
                lvLoadView.showLoadPage(null);

            }

            @Override
            public void onError(VolleyError error) {
                lvLoadView.showErrorPage(getResources().getString(R.string.neterror_click));
            }

            @Override
            public void onSuccess(DataBean<ImageDetailBean> response) {
                if (!response.noError()) {//数据错误
                    lvLoadView.showErrorPage(getResources().getString(R.string.dataerror));
                } else {
                    imageDetailBean = response.getData();
                    if (imageDetailBean != null && imageDetailBean.getGalleryList() != null) {
                        adapterData(imageDetailBean);
                    } else {
                        lvLoadView.showErrorPage(getResources().getString(R.string.neterror));
                    }
                }
            }
        });

    }

    /**
     * 适配数据
     *
     * @param imageDetailBean
     */
    private void adapterData(ImageDetailBean imageDetailBean) {

        lvLoadView.showSuccess();

        LoadImageUtils.getInstance().loadCircleImage(this.authorHeadView, imageDetailBean.getAuthorHeadPic());
        String commentNum = imageDetailBean.getCommentNum();
        setCommentSum(commentNum);
        if (!TextUtils.isEmpty(imageDetailBean.getShareNum()) && !"0".equals(imageDetailBean.getShareNum())) {
            this.mShareSum.setText(imageDetailBean.getShareNum());
            this.mShareSum.setBackgroundResource(R.drawable.detail_comment_count_bg);
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) this.mShareSum.getLayoutParams();
            if (layoutParams != null) {
                layoutParams.width = RelativeLayout.LayoutParams.WRAP_CONTENT;
                layoutParams.height = RelativeLayout.LayoutParams.WRAP_CONTENT;
                this.mShareSum.setLayoutParams(layoutParams);
            }
        }

        //得到图库的具体信息后才可以分享
        ivShare.setOnClickListener(this);
//        List<GalleryEntity> galleryList = imageDetailBean.getGalleryList();
//        List<RecommendGalleryEntity> recommendGallery = imageDetailBean.getRecommendGallery();
        if (imageDetailAdapter == null) {
//            imageDetailAdapter = new ImageDetailAdapter(galleryList, recommendGallery);
            imageDetailAdapter = new ImageDetailAdapter(imageDetailBean);
            imageDetailAdapter.setImageClickListener(this);
            hackyImageViewPager.setAdapter(imageDetailAdapter);
            hackyImageViewPager.setPageMargin(ViewSizeUtils.dp2px(this, 30));
            //hackyImageViewPager.setPageTransformer();
        } else {
            imageDetailAdapter.notifyDataSetChanged();
        }
//        imageDetailAdapter.setOnPhotoViewClickListener(this);
        //预加载4张
        hackyImageViewPager.setOffscreenPageLimit(3);
        hackyImageViewPager.setCurrentItem(0);

        setData();


    }

    private void setCommentSum(String commentNum) {
        if (tvCommentSum != null) {
            if (!TextUtils.isEmpty(commentNum) && !TextUtils.equals("0", commentNum)) {
                tvCommentSum.setVisibility(View.VISIBLE);
                tvCommentSum.setText(commentNum);
            } else {
                tvCommentSum.setVisibility(View.GONE);
            }
        }
    }

    private String commentNum;

    private void setData() {
        if (imageDetailBean != null && !TextUtils.isEmpty(imageDetailBean.getCommentNum())
                && imageDetailBean.getGalleryList() != null
                && imageDetailBean.getGalleryList().size() > 0) {
            commentNum = imageDetailBean.getCommentNum();
            boolean isCollect = imageDetailBean.getIsCollect();

            tvCommentSum.setText(commentNum);
            ivCollection.setSelected(imageDetailBean.getIsCollect());


            //设置第一次的图片描述
            setContentTxt(0, imageDetailBean.getGalleryList());
        }

    }


    /**
     * 初始化控件
     */
    private void initView() {
        //最外层的父控件
        vrlContainer = (VerticalRelativeLayout) findViewById(R.id.vrl_container);
        vrlContainer.setOnTouchMoveListener(this);

        //透明的title
        trspTitle = (LinearLayout) findViewById(R.id.ll_title);
        View titleBg = findViewById(R.id.view_bg);
        titleBg.setVisibility(View.VISIBLE);
        titleBg.setBackgroundColor(getResources().getColor(R.color.common_black_transparent70per));
        //底部操作栏
        llBottom = (LinearLayout) findViewById(R.id.ll_botm);
        hackyImageViewPager = (HackyViewPager) findViewById(R.id.hvp_imagecontainer);
        tvComment = (TextView) findViewById(R.id.tv_comment);
        tvCommentSum = (TextView) findViewById(R.id.tv_commentSum);
        mShareSum = (TextView) findViewById(R.id.tv_shareSum);
        rlCommentContainer = (RelativeLayout) findViewById(R.id.imagedetail_comment_layout);
        ivCollection = (ImageView) findViewById(R.id.iv_collect);
        ivShare = (ImageView) findViewById(R.id.iv_share);
        lvLoadView = (LoadView) findViewById(R.id.lv_loadview);
//        svContent = (ScrollView) findViewById(R.id.sv_content);
        tvContent = (TextView) findViewById(R.id.tv_content);
        authorHeadView = (CustomImageView) findViewById(R.id.civ_author);
        this.authorHeadView.setOnClickListener(this);
        this.authorHeadView.setVisibility(View.VISIBLE);
        //crPv = (SectorProgressView) findViewById(R.id.crpv);

        //将发表框的宽度设为屏幕一半
        ViewGroup.LayoutParams params = tvComment.getLayoutParams();
        params.width = ViewSizeUtils.getWidthPixels() / 2;

        //动画

        inScreenTop = AppAnimotionuUtils.getInScreenTop();
        outScreenTop = AppAnimotionuUtils.getOutScreenTop();


        //title
        ivAppLeft = (ImageView) findViewById(R.id.iv_appleft);
        ivAppLeft.setImageResource(R.drawable.infor_picture_shut);
        tvAppTitle = (TextView) findViewById(R.id.tv_apptitle);
        ivAppRight = (ImageView) findViewById(R.id.tv_appright);
        tvAppTitle.setVisibility(View.GONE);
        ivAppRight.setImageResource(R.drawable.detail_menu_white_selector);


    }

    /**
     * 初始化监听
     */
    private void initListener() {
        lvLoadView.setErrorPageClickListener(this);
        tvComment.setOnClickListener(this);

        rlCommentContainer.setOnClickListener(this);
        ivCollection.setOnClickListener(this);

        ivAppRight.setOnClickListener(this);
        hackyImageViewPager.addOnPageChangeListener(this);

    }


    @Override
    public void onClick(View v) {
        if (v == null) return;
        switch (v.getId()) {
            case R.id.error_page://loadview的点击
                loadData();
                break;
            case R.id.tv_comment://发表评论的点击事件
                showCommentDialog();
                break;

            case R.id.imagedetail_comment_layout://跳转评论的点击
                if (TextUtils.isEmpty(articleId)) return;

                if (intent != null) {
                    intent.setClass(this, ImageDetailCommentActivity.class);
                    startActivityForResult(intent, Config.ResultCode.REQUESTCODE_1);
                } else {
                    Intent intentComment = new Intent();
                    intentComment.setClass(this, ImageDetailCommentActivity.class);
                    intentComment.putExtra(Config.Extra.PARAMETER1, articleId);
                    startActivityForResult(intentComment, Config.ResultCode.REQUESTCODE_1);
                }
                break;
            case R.id.iv_collect://收藏
                save();
                break;
            case R.id.iv_share://分享
                share();
                break;
            case R.id.tv_appright://右上角
                share();
                break;

            case R.id.tv_cancel:
                DialogUtils.getInstance().dismissCDialog();
                break;
            case R.id.tv_save:
                DialogUtils.getInstance().dismissCDialog();
                downLoadImage();

                break;
            case R.id.civ_author:
                if (imageDetailBean != null) {
                    Intent intent = new Intent(this, MyHomepageDynamicActivity.class);
                    intent.putExtra(Config.Extra.PARAMETER1, imageDetailBean.getAuthorId());
                    startActivity(intent);
                }
                break;
        }
    }

    /**
     * 下载图片
     */
    private void downLoadImage() {
        if (imageDetailBean == null
                || imageDetailBean.getGalleryList() == null
                || imageDetailBean.getGalleryList().isEmpty()) {
            return;
        }
        PermissionUtils.permission(PermissionConstants.STORAGE).callback(new PermissionUtils.SimpleCallback() {
            @Override
            public void onGranted() {
                String fileName = imageDetailBean.getGalleryList().get(currentPosition).getGalleryUrl().substring(imageDetailBean.getGalleryList().get(currentPosition).getGalleryUrl().lastIndexOf("/") + 1) + ".jpg";
                OkHttp3Helper.getInstance().downAsynFile(imageDetailBean.getGalleryList().get(currentPosition).getGalleryUrl(),
                        AppConfigTools.USERSAVEIMG, fileName, onDownLoadResponCallBack);
                ToastUtils.makeText("开始下载");
            }

            @Override
            public void onDenied() {

            }
        }).request();

    }


    /**
     * 下载的回调
     */
    private OkHttp3Helper.OnDownLoadResponCallBack onDownLoadResponCallBack = new OkHttp3Helper.OnDownLoadResponCallBack() {
        @Override
        public void onStart() {
            super.onStart();
        }

        @Override
        public void onFailure() {
            super.onFailure();
            handler.sendEmptyMessage(FAIL);
        }

        @Override
        public void onSucess(File file) {
            super.onSucess(file);
            if (file == null) {
                handler.sendEmptyMessage(FAIL);
                return;
            }
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
            Message msg = Message.obtain();
            msg.what = SUCCESS;
            msg.obj = file.getAbsolutePath();
            handler.sendMessage(msg);
        }
    };


    /**
     * 分享
     */
    private void share() {

        initShare();
        mShareUtils.showShareDialog(this.imageDetailBean, TypeConstant.PAGE_NEWS);
    }

    private void initShare() {

        if (mShareUtils == null) {
            mShareUtils = new AppShareUtils(this);
        }
    }


    /**
     * 收藏
     */
    private void save() {
        if (imageDetailBean == null || this.imageDetailBean == null) {
            ToastUtils.makeText(R.drawable.handle_fail, "操作失败");
            return;
        }
        Object isSave = this.ivCollection.getTag();//获取是否收藏标识
        if (isSave == null || !((boolean) isSave)) {
            //如果没有收藏 则 进行收藏操作
            boolean b = CollectUtils.getInstance().saveNews(imageDetailBean.getArticleId());
            if (b) {
                ToastUtils.makeText(R.drawable.infor_pop_collection_yes, "收藏成功");
                this.ivCollection.setImageResource(R.drawable.infor_tabbar_collection_vis);
                this.ivCollection.setTag(true);
            } else {
                ToastUtils.makeText(R.drawable.handle_fail, "操作失败");
            }
        } else {
            //如果已收藏 则 进行取消操作
            boolean b = CollectUtils.getInstance().deleteSaveNews(imageDetailBean.getArticleId());
            if (b) {
                ToastUtils.makeText(R.drawable.infor_pop_collection_cancel, "取消收藏");
                this.ivCollection.setImageResource(R.drawable.detail_collect_white_selector);
                this.ivCollection.setTag(false);
            } else {
                ToastUtils.makeText(R.drawable.handle_fail, "操作失败");
            }
        }

    }


    /**
     * 展示评论框
     */
    private void showCommentDialog() {
        if (mCommentListener == null) {
            mCommentListener = new CommentListener() {
                @Override
                public void commentStart() {
                }

                @Override
                public void commentFail(VolleyError volley) {
                }

                @Override
                public void commentSuccess(NewsComment newsComment) {
                    if (tvCommentSum != null) {
                        int num = StringUtils.toInt(tvCommentSum.getText().toString(), 0);
                        tvCommentSum.setText("" + (++num));
                        if (tvCommentSum.getVisibility() == View.GONE) {
                            tvCommentSum.setVisibility(View.VISIBLE);
                        }
                    }
                }
            };
        }

        CommentUtils.getInstance().showDialog(this, mPageName, articleId, null, mCommentListener);
    }


    /**
     * 获取请求参数的方法
     * <p/>
     * 有数据源的时候传数据源
     * 是登录状态,传uid
     *
     * @param params
     */
    public void getParams(Map<String, String> params) {
        params.clear();

        if (TextUtils.isEmpty(articleId)) {
            ToastUtils.makeText(getResources().getString(R.string.neterror));
            return;
        }
        params.put("articleId", articleId);
        if (!TextUtils.isEmpty(pageSourceType)) {
            params.put("sourceType", pageSourceType);
        }
        if (UserInforManager.getInstance().isLogin()) {
            params.put("uid", UserInforManager.getInstance().getUserInfor().getUid());
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

    }


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
        this.currentPosition = position;
        if (imageDetailBean != null //图库实体不为null
                && imageDetailBean.getGalleryList() != null //图库的集合不为null
                && imageDetailBean.getGalleryList().size() > 0) {//图库的集合size大于0
            if (position <= imageDetailBean.getGalleryList().size() - 1) {
                List<GalleryEntity> galleryList = imageDetailBean.getGalleryList();
                tvContent.setVisibility(View.VISIBLE);
                setContentTxt(position, galleryList);
                if (authorHeadView.getVisibility() == View.GONE) {
                    authorHeadView.setVisibility(View.VISIBLE);
                }
            } else {
                //有相关图集推荐,将描述隐藏掉,并且给他设置点击事件
//                int visibility = svContent.getVisibility();
                imageAboutView = imageDetailAdapter.getImageAboutView();
                if (imageAboutView != null) {
                    imageAboutView.setOnImageDetailAboutClickListener(this);
                }
                tvContent.setVisibility(View.GONE);
                authorHeadView.setVisibility(View.GONE);
                setContent();

            }
        }
    }


    @Override
    public void onPageScrollStateChanged(int state) {
        if (imageDetailBean == null) return;
        switch (state) {
            case ViewPager.SCROLL_STATE_DRAGGING:
                misScrolled = false;
                break;
            case ViewPager.SCROLL_STATE_SETTLING:
                misScrolled = true;
                break;
            case ViewPager.SCROLL_STATE_IDLE:

                if (hackyImageViewPager.getCurrentItem() == hackyImageViewPager.getAdapter().getCount() - 1
                        && !misScrolled
                        && !TextUtils.isEmpty(imageDetailBean.getNextArticleId())) {
//                    ToastUtils.makeText(getResources().getString(R.string.common_nomore));
                    jumpToImageDetailActivity(imageDetailBean.getNextArticleId());


                }
                misScrolled = true;
                break;
        }
    }


    /**
     * 设置图库的描述
     *
     * @param position
     * @param galleryList
     */
    private void setContentTxt(int position, List<GalleryEntity> galleryList) {

        String strContent = String.valueOf((position + 1)) + "/" + galleryList.size() + "  " + galleryList.get(position).getGalleryTitle();
        String pageNum = String.valueOf((position + 1)) + "/" + imageDetailBean.getGalleryList().size() + "  ";
        String currentPageNum = String.valueOf((position) + 1) + "";

        SpannableString styledText = new SpannableString(strContent);

        styledText.setSpan(new TextAppearanceSpan(this, R.style.style_font_size_18), 0, currentPageNum.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        styledText.setSpan(new TextAppearanceSpan(this, R.style.style_font_size_14), currentPageNum.length(), pageNum.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        styledText.setSpan(new TextAppearanceSpan(this, R.style.style_font_size_16), pageNum.length(), strContent.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        if (tvContent != null) {
            tvContent.setText(styledText, TextView.BufferType.SPANNABLE);
        }

    }

    /**
     * 相关图集 页面 设为空
     */
    private void setContent() {
        tvContent.setText("");
    }


//    /**
//     * 点击viewpager中photoview的点击回调
//     */
//    @Override
//    public void onClickDoSt() {
//        showOrHintView();
//    }

    @Override
    public void onOneStepClick() {
        showOrHintView();
    }

    /**
     * 长按photoview的点击回调
     */
    @Override
    public void onLongStepClick() {

        if (downLoadView == null) {
            downLoadView = LayoutInflater.from(this).inflate(R.layout.dialog_save_image, null);
            TextView cancel = (TextView) downLoadView.findViewById(R.id.tv_cancel);
            TextView save = (TextView) downLoadView.findViewById(R.id.tv_save);
            cancel.setOnClickListener(this);
            save.setOnClickListener(this);
        }
        if (dialogParams == null) {
            dialogParams = new HashMap<>();
            dialogParams.put("anim", R.style.dialogWindowAnim);
            dialogParams.put("local", Gravity.BOTTOM);
        }

        DialogUtils.getInstance().showCDialog(downLoadView, this, dialogParams);


    }


    /**
     * 获取上一个页面的intent数据
     */
    private void getIntentData() {
        intent = getIntent();
        if (intent == null) {
            return;
        }
        //获取文章id,文章源
        articleId = intent.getStringExtra(Config.Extra.PARAMETER1);
        pageSourceType = intent.getStringExtra(Config.Extra.PARAMETER2);
    }


    /**
     * 展示或者隐藏图片的描述
     */
    private void showOrHintView() {
        if (!isFullScreen) {
            isFullScreen = true;
            finishAnimaTopOrBottom(llBottom, false);
            finishAnimaTopOrBottom(trspTitle, true);
        } else {
            isFullScreen = false;
            resetTopAndBotm(llBottom, false);
            resetTopAndBotm(trspTitle, true);

        }
    }

    /************************相关图库的回调*******************************/
    /**
     * 图库换一换的方法
     */
    @Override
    public void change() {
        if (TextUtils.isEmpty(articleId)) return;
        Map<String, String> params = new HashMap<>();
        params.put("articleId", articleId);
        addPostRequest(URIContant.IMAGEABOUT_CHANGE,
                new TypeToken<DataBean<List<RecommendGalleryEntity>>>() {
                }.getType(), params,
                new HttpListener<DataBean<List<RecommendGalleryEntity>>>() {
                    @Override
                    public void onStart() {
                        super.onStart();
                        DialogUtils.getInstance().showProgressDialog(ImageDetailActivity.this);
                    }

                    @Override
                    public void onError(VolleyError error) {
                        DialogUtils.getInstance().dismissProgressDialog();
                        ToastUtils.makeText(getResources().getString(R.string.neterror));
                    }

                    @Override
                    public void onSuccess(DataBean<List<RecommendGalleryEntity>> response) {
                        if (!response.noError()) {//有问题
                            DialogUtils.getInstance().dismissProgressDialog();
                            ToastUtils.makeText(getResources().getString(R.string.neterror));
                        } else {
                            List<RecommendGalleryEntity> RecommendGalleryList = response.getData();
                            DialogUtils.getInstance().dismissProgressDialog();
                            if (RecommendGalleryList != null && RecommendGalleryList.size() > 0) {
                                imageAboutView.notifyData(RecommendGalleryList);
                            }

                        }
                    }
                });

    }

    /**
     * 下一个图集的方法
     */
    @Override
    public void nextImage() {
        if (imageDetailBean == null) return;
        String nextArticleId = imageDetailBean.getNextArticleId();
        if (!TextUtils.isEmpty(nextArticleId)) {
            jumpToImageDetailActivity(nextArticleId);
        }

    }

    /**
     * gridview的回调
     */
    @Override
    public void gridViewClick(View view) {
        if (view.getTag(R.id.aboutImageGridView) instanceof RecommendGalleryEntity) {
            RecommendGalleryEntity recommendGalleryEntity = (RecommendGalleryEntity) view.getTag(R.id.aboutImageGridView);
            String articleId = recommendGalleryEntity.getArticleId();
            if (!TextUtils.isEmpty(articleId)) {
                jumpToImageDetailActivity(articleId);
            }

        }
    }

    /**
     * 跳转图集
     *
     * @param articleId
     */
    private void jumpToImageDetailActivity(String articleId) {
        Intent intent = new Intent();
        intent.setClass(this, ImageDetailActivity.class);
        intent.putExtra(Config.Extra.PARAMETER1, articleId);
        startActivity(intent);
    }

    /************************
     * 先相关图库的回调
     *******************************/


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //设置友盟回调
        try {
            if (data != null) {
                UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //

    }


    @Override
    public void smoothMove(int diffY, int totalDiff) {
        if (heightPixels == 0) {
            heightPixels = ViewSizeUtils.getHeightPixels();
        }
        changeAlpha(totalDiff);
        imageTranslate(hackyImageViewPager, diffY);
        titleTranslate(trspTitle, diffY, totalDiff);
        descTranslate(llBottom, diffY, totalDiff);

    }


    @Override
    public void smoothUp(int totalDiffY) {

        //判断滑动的距离，如果超出一定的范围，则将内容划出，并退出当前的activity，否则，就复原
        if (Math.abs(totalDiffY) > heightPixels / persent) {
            finishAnimaImage(hackyImageViewPager, totalDiffY);
            finishAnimaTopOrBottom(trspTitle, true);
            finishAnimaTopOrBottom(llBottom, false);
            changeAlphaAnimal(totalDiffY);
        } else {
            resetTopAndBotm(hackyImageViewPager, true);
            resetTopAndBotm(trspTitle, true);
            resetTopAndBotm(llBottom, false);
            changeAlphaAnimal(totalDiffY);

        }


    }

    private void finishAnimaTopOrBottom(final View view, final boolean isTop) {
        int height = view.getHeight();
        int padding;
        ValueAnimator valueAnimator;
        if (isTop) {
            padding = view.getPaddingTop();
            valueAnimator = ValueAnimator.ofInt(padding, -height + padding);

        } else {
            padding = view.getPaddingBottom();
            valueAnimator = ValueAnimator.ofInt(padding, -height + padding);
        }


        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int animatedValue = (int) animation.getAnimatedValue();
                if (isTop) {
                    view.setPadding(0, animatedValue, 0, -animatedValue);
                } else {
                    view.setPadding(0, 0, 0, animatedValue);
                }

            }
        });
        valueAnimator.addListener(isVisibleListener);
        valueAnimator.setDuration(AnimalDuration);
        valueAnimator.start();


    }


    Animator.AnimatorListener isVisibleListener = new Animator.AnimatorListener() {
        @Override
        public void onAnimationStart(Animator animation) {
            if (!isFullScreen) {
                if (llBottom != null && trspTitle != null) {
                    if (llBottom.getVisibility() == View.GONE) {
                        llBottom.setVisibility(View.VISIBLE);
                    }
                    if (trspTitle.getVisibility() == View.GONE) {
                        trspTitle.setVisibility(View.VISIBLE);
                    }
                }
            }

        }

        @Override
        public void onAnimationEnd(Animator animation) {
            if (isFullScreen) {
                if (llBottom != null && trspTitle != null) {
                    if (llBottom.getVisibility() == View.VISIBLE) {
                        llBottom.setVisibility(View.GONE);
                    }
                    if (trspTitle.getVisibility() == View.VISIBLE) {
                        trspTitle.setVisibility(View.GONE);
                    }
                }
            }

        }

        @Override
        public void onAnimationCancel(Animator animation) {

        }

        @Override
        public void onAnimationRepeat(Animator animation) {

        }
    };


    private void finishAnimaImage(final View view, float totalDiffY) {
        int height = view.getHeight();
        ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
        if (layoutParams != null && layoutParams instanceof ViewGroup.MarginLayoutParams) {
            final ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) layoutParams;
            int topMargin = marginLayoutParams.topMargin;
            ValueAnimator valueAnimator;
            if (totalDiffY > 0) {
                valueAnimator = ValueAnimator.ofInt(topMargin, height);
            } else {
                valueAnimator = ValueAnimator.ofInt(topMargin, -height);
            }
            valueAnimator.setDuration(AnimalDuration);
            valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    int animatedValue = (int) animation.getAnimatedValue();
                    marginLayoutParams.setMargins(0, animatedValue, 0, -animatedValue);
                    view.setLayoutParams(marginLayoutParams);

                }
            });

            valueAnimator.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    ActivityUtils.finishActivity(ImageDetailActivity.this);
                    overridePendingTransition(0, R.anim.base_alpha_out);
                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
            valueAnimator.start();
        }
    }


    /**
     * 随手势滑动 背景变色
     *
     * @param totalDiff
     */
    private void changeAlpha(float totalDiff) {
        float rate = (heightPixels - Math.abs(totalDiff)) / heightPixels;
        //进行平滑的动画
        findViewById(R.id.image_bg).setAlpha(rate);
    }


    /**
     * 更改背景透明度的动画
     *
     * @param totalDiff
     */
    private void changeAlphaAnimal(float totalDiff) {
        final View viewBg = findViewById(R.id.image_bg);
        float alpha = viewBg.getAlpha();
        ValueAnimator valueAnimator;
        if (Math.abs(totalDiff) > heightPixels / persent) {//渐变成透明色
            valueAnimator = ValueAnimator.ofFloat(alpha, 0);
            valueAnimator.setDuration(AnimalDuration);
            valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    float animatedValue = (float) animation.getAnimatedValue();
                    viewBg.setAlpha(animatedValue);
                }
            });
            valueAnimator.start();
        } else {//渐变成黑色
            valueAnimator = ValueAnimator.ofFloat(alpha, 1);
            valueAnimator.setDuration(AnimalDuration);
            valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    float animatedValue = (float) animation.getAnimatedValue();
                    viewBg.setAlpha(animatedValue);
                }
            });
            valueAnimator.start();
        }


    }


    /**
     * 复原的动画
     *
     * @param view
     */
    private void resetTopAndBotm(final ViewGroup view, final boolean top) {
        int padding;
        ValueAnimator valueAnimator;
        if (top) {
            padding = view.getPaddingTop();
        } else {
            padding = view.getPaddingBottom();
        }
        valueAnimator = ValueAnimator.ofInt(padding, 0);
        valueAnimator.setDuration(AnimalDuration);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int animatedValue = (int) animation.getAnimatedValue();
                if (top) {
                    view.setPadding(0, animatedValue, 0, -animatedValue);
                } else {
                    view.setPadding(0, 0, 0, animatedValue);
                }

            }
        });
        valueAnimator.addListener(isVisibleListener);
        valueAnimator.start();


    }

    /**
     * 图片随手势滑动
     *
     * @param view
     * @param diffY
     */
    private void imageTranslate(ViewGroup view, int diffY) {
        view.setPadding(0, view.getPaddingTop() + diffY, 0, view.getPaddingBottom() - diffY);
        view.requestLayout();
    }

    /**
     * 描述随手势滑动
     *
     * @param view
     * @param diffY
     * @param totalDiff
     */
    private void descTranslate(ViewGroup view, int diffY, int totalDiff) {
        int paddingBottom;
        if (diffY > 0) {//想下滑动
            if (totalDiff > 0) {//要向下走
                paddingBottom = view.getPaddingBottom() - diffY;
            } else if (totalDiff < 0) {
                paddingBottom = view.getPaddingBottom() + diffY;
            } else {
                paddingBottom = 0;
            }
        } else if (diffY < 0) {//向上滑动
            if (totalDiff > 0) {//向下走
                paddingBottom = view.getPaddingBottom() - diffY;
            } else if (totalDiff < 0) {//向上走
                paddingBottom = view.getPaddingBottom() + diffY;
            } else {
                paddingBottom = 0;
            }
        } else {
            paddingBottom = view.getPaddingBottom();
        }
        if (paddingBottom > 0) {
            paddingBottom = 0;
        }

        view.setPadding(0, 0, 0, paddingBottom);
        view.requestLayout();

    }


    /**
     * title随手势滑动
     *
     * @param view
     * @param diffY
     * @param totalDiff
     */
    private void titleTranslate(ViewGroup view, int diffY, int totalDiff) {
        int paddingTop;
        if (diffY > 0) {//向下滑动
            if (totalDiff > 0) {//图片是从原始位置往向下放屏幕外滑动，title应该向上滑动
                paddingTop = view.getPaddingTop() - diffY;
            } else if (totalDiff < 0) {//图片从屏幕上方 往原始位置滑动，title 应该向下 滑动
                paddingTop = view.getPaddingTop() + diffY;
            } else {
                paddingTop = 0;
            }
        } else if (diffY < 0) {//向上滑动-------diffy < 0
            if (totalDiff > 0) {//图片从屏幕下方 往原始位置滑动，title往下滑动
                paddingTop = view.getPaddingTop() - diffY;
            } else if (totalDiff < 0) {//图片从原始位置 往屏幕上方滑动，title 向上滑动
                paddingTop = view.getPaddingTop() + diffY;
            } else {
                paddingTop = 0;
            }
        } else {
            paddingTop = view.getPaddingTop();
        }
        if (paddingTop > 0) {
            paddingTop = 0;
        }

        view.setPadding(0, paddingTop, 0, 0);
        view.requestLayout();

    }
}
